<?php

class Api {

    protected $db;       //数据库
    protected $isdebug = false;    //是否debug
    protected $check_time = true;   //是否时间检查
    protected $check_limit_time = 100;  //检查间隔时间,秒
    protected $source = array();    //原数据
    protected $outdata = array();   //输出数据
    protected $act;      //请求方法
    protected $action;      //执行函数
    protected $lib;      //对应api库

    public function __construct($db, $data) {
	$this->db = $db;
	$this->source = $data;
	$this->act = trim($data['act']);
    }

    public function run() {
	$data = $this->source;
	$systime = intval($data['systime']);

	//时间检测
	if ($this->check_time) {
	    if (time() - $systime > $this->check_limit_time) {      //600秒访问时效
		$this->outdata = array('status' => '0', 'title' => '错误提示', 'tips' => '访问超时');
		$this->output();
	    }
	}

	//获取执行方法及对应的类
	$rs = $this->get_action_by_act($this->act);
	if ($rs) {

	    $lib = $this->lib;
	    $action = $this->action;
	    if ($lib !== 'common_api') {      //避免重复载入
		load_file("common_api", LIB_PATH);
	    }
	    load_file($lib, LIB_PATH);      //引用对应的类
	    $main = new $lib($this->db);
	    $this->outdata = $main->$action($data);    //执行对应的方法
	} else {
	    $this->outdata = array('status' => '0', 'title' => '错误提示', 'tips' => '系统出错');
	}

	//输出结果
	if ($this->isdebug) {
	    $this->debug_data();
	    exit;
	}
	return $this->outdata;
    }

    private function get_action_by_act($act) {
	$action_array_settting = array(
	    'check_version' => array('lib' => 'common', 'action' => 'check_version'),
	    'get_page' => array('lib' => 'ad', 'action' => 'get_page'),
	    //用户	
	    'user_login' => array('lib' => 'user', 'action' => 'user_login'),
		'check_user_token' => array('lib' => 'user', 'action' => 'check_user_token'),
	    'set_apk_log' => array('lib' => 'user', 'action' => 'set_apk_log'),
		'set_ios_log' => array('lib' => 'common', 'action' => 'set_ios_log'),



	);

	if (isset($action_array_settting[$act])) {
	    $this->action = $action_array_settting[$act]['action'];
	    $this->lib = $action_array_settting[$act]['lib'] . '_api';
	    return true;
	} else {
	    return false;
	}
    }

    public function __destruct() {
	unset($this->db);
    }

    private function output() {
	if ($this->isdebug) {
	    $this->debug_data();
	    exit;
	}
	return $this->outdata;
    }

    private function debug_data() {
	$msg = "<pre>";
	$msg .= "\n 数据源: " . print_r($this->source, true);
	$msg .= "\n 请求类: " . $this->lib;
	$msg .= "  使用方法: " . $this->action;
	$msg .= "\n\n 输出: " . print_r($this->outdata, true);
	$msg .= "</pre>";
	echo $msg;
    }

    public function debug($debug = true, $sqldebug = false) {
	$this->isdebug = $debug;
	$this->db->debug($sqldebug);
    }

}

?>